import React, { useEffect, useState } from "react";
import { Table, Tag, Button, notification } from "antd";
import axios from "axios";
import { AUDIT_LIST } from "../../../util/const";

export default function AuditList(props) {
  const [dataSource, setdataSource] = useState([]);
  const { username } = JSON.parse(localStorage.getItem("token"));
  useEffect(() => {
    axios
      .get(
        `/news?_expand=category&author=${username}&auditState_ne=0&publishState_lte=1`
      )
      .then(({ data }) => {
        setdataSource(data);
      });
  }, [username]);
  const auditColorList = ["#333", "orange", "green", "red"];
  const columns = [
    {
      title: "新闻标题",
      dataIndex: "title",
      render(title, item) {
        return <a href={`/#/news-manage/preview/${item.id}`}>{title}</a>;
      }
    },
    {
      title: "作者",
      dataIndex: "author"
    },
    {
      title: "新闻分类",
      dataIndex: "category",
      render(category) {
        return category.title;
      }
    },
    {
      title: "审核状态",
      dataIndex: "auditState",
      render(auditState) {
        return (
          <Tag color={auditColorList[auditState]}>{AUDIT_LIST[auditState]}</Tag>
        );
      }
    },
    {
      title: "操作",
      dataIndex: "auditState",
      render(auditState, item) {
        return (
          <div>
            {auditState === 1 && (
              <Button danger onClick={() => revoke(item)}>
                撤销
              </Button>
            )}
            {auditState === 2 && (
              <Button type="primary" onClick={() => publish(item)}>
                发布
              </Button>
            )}
            {auditState === 3 && (
              <Button onClick={() => modify(item)}>修改</Button>
            )}
          </div>
        );
      }
    }
  ];
  const revoke = item => {
    axios
      .patch(`/news/${item.id}`, {
        auditState: 0
      })
      .then(() => {
        props.history.push("/news-manage/draft");
        notification.info({
          message: "通知",
          description: `您的新闻已撤销到[草稿箱中]`,
          placement: "bottomRight"
        });
      });
  };
  const publish = item => {
    axios
      .patch(`/news/${item.id}`, {
        publishState: 2,
        publishTime: Date.now()
      })
      .then(() => {
        props.history.push("/publish-manage/published");
        notification.info({
          message: "通知",
          description: `您的新闻已发布,可以在[发布管理/已发布]中查看您的新闻`,
          placement: "bottomRight"
        });
      });
  };
  const modify = item => {
    props.history.push(`/news-manage/update/${item.id}`);
  };
  return (
    <Table
      dataSource={dataSource}
      columns={columns}
      pagination={{ pageSize: 5 }}
      rowKey={item => item.id}
    />
  );
}
